<template>
  <div class="app-container home">
    <el-card shadow="hover">
      <el-container>
        <el-main>
          <el-row :gutter="24" style="margin-top: 20px;">
            <!-- 角色模块 -->
            <el-col :span="8">
              <!-- 搜索框 -->
              <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
                <el-form-item label="角色名称" prop="roleName">
                  <el-input v-model="queryParams.roleName" placeholder="请输入角色名称" clearable @keyup.enter="handleQuery" />
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="handleQuery" icon="Search">搜索</el-button>
                  <el-button @click="resetQuery" icon="Refresh">重置</el-button>
                </el-form-item>
              </el-form>

              <!-- 角色列表 -->
              <el-table ref="roleTableRef" highlight-current-row v-loading="loading" :data="roleList" @current-change="handleRoleCurrentChange">
                <el-table-column label="角色名称" prop="roleName" :show-overflow-tooltip="true" width="150" />
                <el-table-column label="权限字符" prop="roleKey" :show-overflow-tooltip="true" width="200" />
              </el-table>

              <!-- 分页 -->
              <pagination
                v-if="total > 0"
                v-model:total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                layout="total, sizes, prev, pager, next"
                @pagination="getRoleList"
              />
            </el-col>

            <!-- 应用模块 -->
            <el-col :span="8">
              <el-form :model="form" :rules="rules" v-loading="sheetAuthLoading" label-width="100px">

                <el-form-item label="按钮权限" prod="sheetButtonId">
                  <el-tree
                    class="tree-border"
                    show-checkbox multiple clearable filterable
                    :data="sheetButtonList"
                    :render-after-expand="false"
                    node-key="value"
                    ref="treeRef"
                  ></el-tree>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" :loading="buttonLoading" @click="saveSheetAuth()" v-hasPermi="['system:role:sheetAuth']">保存</el-button>
                </el-form-item>

              </el-form>

            </el-col>

          </el-row>

        </el-main>
      </el-container>
    </el-card>
  </div>
</template>


<script setup name="SheetAuth" lang="ts">
import { listRole } from "@/api/system/role";
import { RoleForm, RoleQuery, RoleVO } from "@/api/system/role/types";
import { getSheetButtonList, saveSheetAuthData } from "@/api/sheet/sheetAuth";
import { SearchDataSourceDto } from "@/api/sheet/platform/list/types";
import { SheetButtonAuthForm } from "@/api/sheet/sheetAuth/types";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const buttonLoading = ref(false);
const sheetAuthLoading = ref(false);
const treeRef = ref<ElTreeSelectInstance>();

/** 角色相关参数 */
const roleList = ref<RoleVO[]>();
const loading = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const initForm: RoleForm = {
  roleId: undefined,
  roleSort: 1,
  status: '0',
  roleName: '',
  roleKey: '',
  menuCheckStrictly: true,
  deptCheckStrictly: true,
  remark: '',
  dataScope: '1',
  menuIds: [],
  deptIds: [],
};
const data = reactive<PageData<RoleForm, RoleQuery>>({
  form: { ...initForm },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    roleName: '',
    roleKey: '',
    status: '',
  },
  rules: {
    roleName: [{ required: true, message: "角色名称不能为空", trigger: "blur" }],
    roleKey: [{ required: true, message: "权限字符不能为空", trigger: "blur" }],
    roleSort: [{ required: true, message: "角色顺序不能为空", trigger: "blur" }]
  }
});
const { form, queryParams, rules } = toRefs(data);
const currentRoleRow = ref();
/** 应用按钮列表 */
const sheetButtonList = ref<SearchDataSourceDto[]>([]);

/**
 * 查询角色列表
 */
const getRoleList = () => {
  loading.value = true
  listRole(queryParams.value).then(res => {
    roleList.value = res.rows
    total.value = res.total
    loading.value = false
  })
}

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getRoleList();
}

/** 重置 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}


/** 当前选中角色 */
const handleRoleCurrentChange = (val: RoleVO) => {
  currentRoleRow.value = val
  getSheetButtonData(val.roleId);
}

/**
 * 查询应用按钮列表
 */
const getSheetButtonData = async (roleId: string | number) => {
  sheetAuthLoading.value = true;
  const res = await getSheetButtonList(roleId);
  sheetButtonList.value = res.data.dataSourceList;
  res.data.checkedKeys.forEach((v) => {
    nextTick(() => {
      treeRef.value?.setChecked(v, true, false);
    })
  })
  sheetAuthLoading.value = false;
}

/** 保存应用授权 */
const saveSheetAuth = async () => {
  buttonLoading.value = true;
  let selectData = treeRef.value?.getCheckedNodes();
  const buttonArray :SheetButtonAuthForm [] = new Array();
  if (selectData.length > 0){
    selectData.forEach((item: SearchDataSourceDto) => {
      let data: SheetButtonAuthForm = {
        roleId: currentRoleRow.value.roleId,
        bindId: item.parentId,
        sheetButtonId: item.value,
        type: 2
      }
      buttonArray.push(data);
    })
  } else {
    let data: SheetButtonAuthForm = {
      roleId: currentRoleRow.value.roleId,
      bindId: 0,
      sheetButtonId: 0,
      type: 2
    }
    buttonArray.push(data);
  }
  await saveSheetAuthData(buttonArray)

  await getSheetButtonData(currentRoleRow.value.roleId);

  buttonLoading.value = false;
  proxy?.$modal.msgSuccess("操作成功")
}


onMounted(() => {
  getRoleList();
});

</script>

